package com.taxshare.log;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Order(1)
@Aspect
@Component
@Slf4j
public class LogAspect {

	@Around("execution(* com.taxshare.*.controller..*.*(..))")
	public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
		long startTime = System.currentTimeMillis(); 
		handleBeforeLog(joinPoint);
		Object result = joinPoint.proceed();
		handleAfterLog(joinPoint, result,startTime);
		return result;
	}

	private void handleBeforeLog(ProceedingJoinPoint joinPoint) {		
		RequestAttributes ra = RequestContextHolder.getRequestAttributes();
	    ServletRequestAttributes sra = (ServletRequestAttributes)ra;
		StringBuffer argsLogInfo = new StringBuffer();
		argsLogInfo.append("请求URL=").append(sra.getRequest().getRequestURI());
		// 获取参数名称
		String[] paramNames = ((MethodSignature) joinPoint.getSignature()).getParameterNames();
		// 获取对应参数值
		Object[] paramValues = joinPoint.getArgs();
		if (paramNames != null && paramNames.length > 0) {
			argsLogInfo.append(",请求参数= [");
			for (int i = 0; i < paramNames.length; i++) {
				argsLogInfo.append(paramNames[i]).append("=").append(paramValues[i]);
				if (i != paramNames.length - 1) {
					argsLogInfo.append(",");
				}
			}
			argsLogInfo.append("]");
		}
		log.info(argsLogInfo.toString());
	}

	private void handleAfterLog(ProceedingJoinPoint joinPoint, Object result,long startTime) {
		if (result != null) {
			long endTime = System.currentTimeMillis(); 
			RequestAttributes ra = RequestContextHolder.getRequestAttributes();
		    ServletRequestAttributes sra = (ServletRequestAttributes)ra;
			StringBuffer logInfo = new StringBuffer();
			logInfo.append("请求URL=").append(sra.getRequest().getRequestURI());
			logInfo.append(",耗时(毫秒)=").append(endTime-startTime);
			logInfo.append(",返回结果=").append(JSONUtil.toJsonStr(result));
			log.info(logInfo.toString());
		}
	}

}
